<?php

namespace app\common\model;

use app\common\traits\TimeCacheTrait;
use think\db\Query;

/**
 * Class Trade
 * @package app\model
 * @property int $id
 * @property string $payMethod
 * @property string $payMethodScene
 * @property string $orderNo
 * @property string $tradeNid
 * @property string $describe
 * @property int $tradeType
 * @property string $tradeTypeClass
 * @property int $questionId
 * @property int $consultingId
 * @property int $serverId
 * @property int $serverSkuId
 * @property int $redPacketId
 * @property int $rewardId
 * @property int $lawCaseId
 * @property int $lawsuitId
 * @property int $landingId
 * @property string $landingType
 * @property int $accountTokenPlanId
 * @property string $sourceId
 * @property float $recharge_balance
 * @property  int $cashTransferId
 * @property int $num
 * @property float $totalMoney
 * @property float $payMoney
 * @property array $attach
 * @property int $startTime
 * @property int $endTime
 * @property string $payMemberType
 * @property int $payMemberId
 * @property int $memberId
 * @property string $payStatus
 * @property int $payExpTime
 * @property int $payTime
 * @property int $refundRequestFirstClickTime
 * @property string $refundStatus
 * @property int $refundCheckUserId
 * @property string $refundCheckStatus
 * @property int $refundRequestTime
 * @property int $refundTime
 * @property string $refundReason
 * @property string $refundNid
 * @property string $refundNo
 * @property string $refundResult
 * @property string $settleStatus
 * @property string $settleConsultingId
 * @property string $settleLawyerId
 * @property string $lawyerMoney
 * @property string $settleLawyerMoney
 * @property string $settleInviterId
 * @property string $settleInviterMoney
 * @property string $settleLawCaseMemberId
 * @property string $settleLawCaseMoney
 * @property string $pf
 * @property string $chain
 * @property int $promotionGroupId
 * @property int $created
 * @property int $updated
 * @method consultingTrade()
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class Trade extends \app\common\model\BaseModel implements ShareableInterface
{
    use TimeCacheTrait;

    //  支付状态 UNPAID 待付款 PAID 已付款 CANCELLED 已取消
    const UNPAID = 'UNPAID';
    const PAID = 'PAID';
    const CANCELLED = 'CANCELLED';
    //  退款状态 NOTREFUND 不退款 REFUNDING 退款中 REFUNDED 已退款 REFUND_FAILED 退款失败
    const NOTREFUND = 'NOTREFUND';
    const REFUNDING = 'REFUNDING';
    const REFUNDED = 'REFUNDED';
    const REFUND_FAILED = 'REFUND_FAILED';
    //  退款审核状态 UNCHECKED 待审核 AGREED 同意 REJECTED 拒绝
    const UNCHECKED = 'UNCHECKED';
    const AGREED = 'AGREED';
    const REJECTED = 'REJECTED';
    //  支付退款结果 refundResult UNSTART 待开始 STARTED 已开始（等待结果） SUCCESS 成功  FAIL 失败
    const UNSTART = 'UNSTART';
    const STARTED = 'STARTED';
    const SUCCESS = 'SUCCESS';
    const FAIL = 'FAIL';
    //  结算状态 NOTSETTLE 不需要结算 UNSETTLED 待结算 SETTLING 结算中 SETTLED 已结算
    const NOTSETTLE = 'NOTSETTLE';
    const UNSETTLED = 'UNSETTLED';
    const SETTLING = 'SETTLING';
    const SETTLED = 'SETTLED';

    // 案如云订单状态 INVITING邀约中 COMPLETED已完成
    const ARY_INVITING = 'INVITING';
    const ARY_COMPLETED = 'COMPLETED';


    protected $name = 'Trade';

    // 设置json类型字段
    protected $json = ['attach'];
    protected $jsonAssoc = true;

    /**
     * 咨询订单（咨询业务的订单，不包含充值和案源消费）
     * 用于管理系统数据统计
     * @param Query $query
     * @return void
     */
    public function scopeConsultingTrade(Query $query)
    {
        $query->whereNotIn('tradeType', [TRADE_CASH, TRADE_BALANCE_RECHARGE, TRADE_TOKEN_RECHARGE, TRADE_SOURCE, TRADE_AXB]);
    }

    // 购买人
    public function member()
    {
        return $this->belongsTo(Member::class, 'memberId', 'id');
    }

    // 所属的咨询
    public function consulting()
    {
        return $this->belongsTo(Consulting::class, 'consultingId', 'id');
    }

    // 购买的案源
    public function lawCase()
    {
        return $this->hasOne(LawCase::class, 'id', 'lawCaseId');
    }

    // 购买的服务
    public function server()
    {
        return $this->hasOne(ConsultingServer::class, 'id', 'serverId');
    }

    public function getCanPunishAttr($value, $data)
    {

        $consultingId = $data['consultingId'] ?? null;
        if (!is_id($consultingId)) {
            return '0';
        }

        $consulting = $this->consulting;
        if (is_null($consulting)) {
            return '0';
        }

        $lawyerId = $consulting->lawyerId;
        if (!is_id($lawyerId)) {
            return '0';
        }

        $lawyer = $consulting->lawyer;
        if (is_null($lawyer)) {
            return '0';
        }

        if ($lawyer->svip != 1) {
            return '0';
        }

        return '1';
    }

    public function getStatusAttr($value, $data)
    {
        return $this->getStatus($data);
    }

    public function getStatusStrAttr($value, $data)
    {
        $status = $this->getStatus($data);
        return ['', '未付款', '进行中', '结算中', '已完成', '申请退款', '已退款', '退款失败', '已取消'][$status] ?? '';
    }

    public function getStatusTimeAttr($value, $data)
    {
        $status = $this->getStatus($data);
        if ($status == '1') {
            return $data['created'];
        } elseif ($status == '2') {
            return $data['payTime'];
        } elseif ($status == '3') {
            return $data['endTime'];
        } elseif ($status == '4') {
            return $data['endTime'];
        } elseif ($status == '5') {
            return $data['refundRequestTime'];
        } elseif ($status == '6') {
            if ($data['refundTime']) {
                return $data['refundTime'];
            } else {
                return $data['refundRequestTime'];
            }
        } elseif ($status == '7') {
            return $data['created'];
        } elseif ($status == '8') {
            return $data['created'];
        }

        return $data['created'];
    }

    private function getStatus($data)
    {
        // 1.未付款 2.进行中 3结算中 4.已完成 5.申请退款 6.已退款 7.退款失败 8.已取消
        if ($data['payStatus'] == Trade::CANCELLED) {
            return '8';
        }

        if ($data['payStatus'] == Trade::UNPAID) {
            return '1';
        }

        if ($data['payStatus'] == Trade::PAID && $data['refundStatus'] == Trade::REFUNDING && $data['refundCheckStatus'] == Trade::UNCHECKED) {
            return '5';
        }

        if ($data['payStatus'] == Trade::PAID && $data['refundStatus'] == Trade::REFUNDED) {
            return '6';
        }

        if ($data['payStatus'] == Trade::PAID && $data['refundStatus'] == Trade::REFUND_FAILED) {
            return '7';
        }

        if ($data['payStatus'] == Trade::PAID && $data['refundStatus'] == Trade::NOTREFUND && is_null($data['endTime'])) {
            return '2';
        }

        if ($data['payStatus'] == Trade::PAID && $data['refundStatus'] == Trade::NOTREFUND && $data['settleStatus'] == Trade::UNSETTLED && !is_null($data['endTime']) && $data['endTime'] <= time()) {
            return '3';
        }

        if ($data['payStatus'] == Trade::PAID && $data['refundStatus'] == Trade::NOTREFUND && in_array($data['settleStatus'], [Trade::NOTSETTLE, Trade::SETTLED]) && !is_null($data['endTime'])) {
            // && $data['endTime'] <= time()
            return '4';
        }

        return '0';
    }

    /**
     * 1对1
     * @return \think\model\relation\HasOne
     */
    //    public function one(){
    //        return $this->hasOne( Test1::class, 'Test1表中的键', 'Trade表中的键');
    //    }

    /**
     * 1对多
     * @return \think\model\relation\HasMany
     */
    //    public function many(){
    //        return $this->hasMany( Test1::class, 'Test1表中的键', 'Trade表中的键');
    //    }

    /**
     * 多对多
     * @return \think\model\relation\BelongsToMany
     */
    //    public function belongs(){
    //        return $this->belongsToMany( Test1::class, '中间表', '中间表中Test1的键', '中间表中Trade的键');
    //    }
}
